package com.dongdong.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //创建shiro过滤器工厂类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加过滤器
        /*不需要登录 直接放过 anon
          必须登录才能访问 authc
          登录也不行 必须有权限 perms
          必须有角色 role
          退出登录 logout
        * */
        Map<String,String> map = new LinkedHashMap<>();
        //放过静态资源
        map.put("/js/**","anon");
        map.put("/img/**","anon");
        map.put("/css/**","anon");
        map.put("/plugins/**","anon");
        //不需要登录可以访问的路径
        map.put("/index","anon");
        map.put("/user/login","anon");
        //拦截所有
        //map.put("/**","authc");
        //退出登录,前面的为方法,后面的为过滤器
        map.put("/logout","logout");
        //登录后才可以展示所有
        map.put("/**","anon");

        factoryBean.setLoginUrl("/user/toLogin");
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
       //关联 realm 我们自己写的登录 授权的逻辑
        securityManager.setRealm(loginRealm);
        return securityManager;
    }
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return  loginRealm;
    }
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //指定加密方式
        matcher.setHashAlgorithmName("MD5");
        //加密次数
        matcher.setHashIterations(3);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }
    //开启shiro标签功能
    @Bean
    public ShiroDialect shiroDialect(){
        return  new ShiroDialect();
    }

}
